package com.demo.function.spring.validator;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;

public class IsMobileValidator implements ConstraintValidator<IsMobile, String>{

    private boolean required = false;

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        //必填
        if (required) {
            return isValidMobile(value);
        } else {//非必填
            if (StringUtils.isBlank(value)) {
                return true;
            } else {
                return isValidMobile(value);
            }
        }
    }

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        // 初始化
        required = constraintAnnotation.required();
    }

    private boolean isValidMobile(String phoneNumber) {
        String regex = "^1[3-9]\\d{9}$";
        return phoneNumber.matches(regex);
    }

}
